package com.ehouse;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

public class Notifications {
	private static Notifications instance;

	public static Notifications getInstance() {
		if (instance == null)
			instance = new Notifications();

		return instance;
	}

	public void sendNotifications(String msg) throws IOException {
		sendAndroidNotifications("eHouse", msg);
		//sendWindowsNotifications("eHouse", msg);
	}

	private void sendAndroidNotifications(String title, String msg) {
		try {
			List<String> registrationIDs = Drivers.getInstance().getAndroidRegIDs();
			if (registrationIDs.isEmpty()) {
				return;
			}
			String authKey = Drivers.getInstance().getAndroidAuthKey();
	
			String IDs = "";
			for (String ID : registrationIDs) {
				System.out.println("Sending notification to " + ID);
				IDs += "\"" + ID + "\",";
			}
			IDs.substring(0, IDs.length() - 1);
	
			String json = "{\"data\": {\"title\":\"" + title + "\",";
			json += "\"content\":\"" + msg + "\",";
			json += "\"badge\":\"" + "0" + "\"},";
			json += "\"registration_ids\": [" + IDs + "] }";
	
			// turn our request String into a byte stream
			byte[] postBytes = json.getBytes("UTF-8");
	
			HttpURLConnection conn = (HttpURLConnection) new URL(
					"https://android.googleapis.com/gcm/send").openConnection();
			conn.setDoOutput(true);
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Content-Type", "application/json");
			conn.setRequestProperty("Charset", "UTF8");
			conn.setRequestProperty("Content-Length",
					Integer.toString(postBytes.length));
			// this is important - make sure you specify type this way
			conn.setRequestProperty("Authorization", "key=" + authKey);
	
			OutputStream os = conn.getOutputStream();
			// now send it
			os.write(postBytes);
			os.flush();
			os.close();
	
			String line;
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					conn.getInputStream()));
			System.out.println("Response:");
			while ((line = reader.readLine()) != null) {
				System.out.println(line);
			}
			reader.close();
		} catch (IOException ex) {
			System.out.println("Error sending Android notification");
			ex.printStackTrace();
		}
	}

	private void sendWindowsNotifications(String title, String subtitle) {
		try {
			List<String> Uris = Drivers.getInstance().getWinPhoneUris();
			if (Uris.isEmpty()) {
				return;
			}
			
			String toastMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
					+ "<wp:Notification xmlns:wp=\"WPNotification\">"
					+ "<wp:Toast>" + "<wp:Text1>" + title + "</wp:Text1>"
					+ "<wp:Text2>" + subtitle + "</wp:Text2>"
					+ "<wp:Param>/Alarm.xaml?Message=" + subtitle
					+ "</wp:Param>" + "</wp:Toast> " + "</wp:Notification>";
	
			for (String subscriptionUri : Uris) {
				System.out.println("Sending notification to " + subscriptionUri);
	
				byte[] notificationMessage = toastMessage.getBytes("UTF8");
	
				HttpURLConnection conn = (HttpURLConnection) new URL(
						subscriptionUri).openConnection();
				conn.setDoOutput(true);
				conn.setRequestMethod("POST");
				conn.setRequestProperty("Content-Type", "text/xml");
				conn.setRequestProperty("X-WindowsPhone-Target", "toast");
				conn.setRequestProperty("X-NotificationClass", "2");
				conn.setRequestProperty("charset", "utf-8");
				conn.setRequestProperty("Content-Length",
						Integer.toString(notificationMessage.length));
	
				OutputStream os = conn.getOutputStream();
				os.write(notificationMessage);
				os.flush();
				os.close();
	
				// TILE NOTIFICATION
	
				// String tileMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
				// +
				// "<wp:Notification xmlns:wp=\"WPNotification\">" +
				// "<wp:Tile>" +
				// "<wp:BackgroundImage>" + "red.jpg" + "</wp:BackgroundImage>" +
				// "<wp:Count>" + "1" + "</wp:Count>" +
				// "<wp:Title>" + title + "</wp:Title>" +
				// "<wp:BackBackgroundImage>" + "blue.jpg" +
				// "</wp:BackBackgroundImage>" +
				// "<wp:BackTitle>" + subtitle + "</wp:BackTitle>" +
				// "<wp:BackContent>" + "" + "</wp:BackContent>" +
				// "</wp:Tile> " +
				// "</wp:Notification>";
	
				// // Set the notification payload to send.
				// byte[] notificationMessage = Encoding.UTF8.GetBytes(tileMessage);
	
				// // Set the web request content length.
				// sendNotificationRequest.ContentLength =
				// notificationMessage.Length;
				// sendNotificationRequest.ContentType = "text/xml";
				// sendNotificationRequest.Headers.Add("X-WindowsPhone-Target",
				// "token");
				// sendNotificationRequest.Headers.Add("X-NotificationClass", "1");
	
				String line;
				BufferedReader reader = new BufferedReader(new InputStreamReader(
						conn.getInputStream()));
				System.out.println("Response:");
				while ((line = reader.readLine()) != null) {
					System.out.println(line);
				}
				reader.close();
			}
		} catch (IOException ex) {
			System.out.println("Error sending WP notification");
			ex.printStackTrace();
		}
	}
}